package com.party.web.web.controller.user;

import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.utils.AESUtil;
import com.party.common.utils.CookieUtil;
import com.party.common.utils.StringUtils;
import com.party.common.utils.UUIDUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.member.ScanLoginOutput;
import com.party.core.model.member.ScanLoginStatus;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.user.LoginBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.UserOperate;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.security.CurrentUser;
import com.party.web.web.security.MyUsernamePasswordToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName ScanLoginController
 * @Description 扫码登录
 * @Author yifeng
 * @Date 2019/1/29 17:26
 **/
@Controller
@RequestMapping("/user/scanLogin")
public class ScanLoginController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LoginBizService loginBizService;

    /**
     * @param loginName 用户名
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 登录
     * @Date 14:17 2019/2/15
     **/
    @UserOperate(moduleName = "用户", behaviorType = BehaviorType.SCAN_LOGIN)
    @ResponseBody
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public AjaxResult scanLogin(String loginName) {
        if (StringUtils.isEmpty(loginName)) {
            return AjaxResult.error("用户名不能为空");
        }

        String currentUserName = null;
        if (null != RealmUtils.getCurrentUser()) {
            currentUserName = RealmUtils.getCurrentUser().getUsername();
        }
        if (StringUtils.isNotEmpty(currentUserName) && currentUserName.equals(loginName)) {
            return AjaxResult.success();
        }
        MyUsernamePasswordToken passwordToken = new MyUsernamePasswordToken(loginName);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(passwordToken);
        } catch (UnknownAccountException ue) {
            logger.error("{}登陆账号不存在", loginName);
            passwordToken.clear();
            currentUser.getSession().removeAttribute(Constant.CURRENT_USER_KEY);
            return AjaxResult.error("账号不存在");
        } catch (IncorrectCredentialsException ie) {
            logger.error("{}登陆密码错误", loginName);
            passwordToken.clear();
            currentUser.getSession().removeAttribute(Constant.CURRENT_USER_KEY);
            return AjaxResult.error("密码错误");
        }
        //获取菜单放到缓存
        CurrentUser newCurrentUser = RealmUtils.getNewCurrentUser();
        String memberId = newCurrentUser.getId();
        redisTemplate.delete("myWebMenuTree_" + memberId);

        return loginBizService.getForwardUrl(passwordToken, currentUser, newCurrentUser);
    }

    /**
     * @param
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 生成登录二维码
     * @Date 14:34 2019/1/29
     **/
    @ResponseBody
    @RequestMapping(value = "generateQRCodeLogin")
    public AjaxResult generateQRCodeLogin(HttpServletResponse response, HttpServletRequest request) {
        try {
            String oldLgToken = CookieUtil.getValue(request, "lgToken");
            if (StringUtils.isNotEmpty(oldLgToken)) {
                String txz123456 = AESUtil.decrypt(oldLgToken, "txz123456");
                loginBizService.deleteCloudQrCode(txz123456);
            }

            String uuid = UUIDUtils.generateRandomUUID();
            String content = "http://a.app.qq.com/o/simple.jsp?pkgname=com.tongxing.mgr&lgToken=" + uuid;
//            String filePath = fileBizService.getUploadCIPath("loginQrCode", Constant.ADMIN_ID);
//            String qrcodeUrl = fileBizService.uploadCloudOut(uuid, filePath, content, null, false, false);
//            if (StringUtils.isEmpty(qrcodeUrl)) {
//                return AjaxResult.error("生成登录二维码异常");
//            }

            ScanLoginOutput loginOutput = new ScanLoginOutput();
            loginOutput.setCode(ScanLoginStatus.NOT_SCAN.getCode()); // 未扫描
            loginOutput.setCreateTime(System.currentTimeMillis()); // 创建时间
            loginOutput.setLgToken(uuid); // 登录token
            loginBizService.setLoginOutRedis(loginOutput);

            String txz123456 = AESUtil.encrypt(uuid, "txz123456");

            // cookie有效期设为1个小时
            CookieUtil.set(response, "lgToken", txz123456, "/web", 3600);

            Map<String, Object> data = Maps.newHashMap();
//            data.put("qrcodeUrl", qrcodeUrl);
            data.put("content", content);
            data.put("lgToken", uuid);
            return AjaxResult.success(data);
        } catch (Exception e) {
            logger.error("生成登录二维码异常", e);
            return AjaxResult.error("生成登录二维码异常");
        }
    }

    /**
     * @param lgToken
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 检查二维码状态
     * @Date 10:26 2019/1/30
     **/
    @ResponseBody
    @RequestMapping(value = "checkQRCodeStatus")
    public AjaxResult checkQRCodeStatus(String lgToken, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(lgToken)) {
                return AjaxResult.error("token为空");
            }
            Map<String, Object> resultMap = loginBizService.checkQRCodeStatus(lgToken, request, response);
            return AjaxResult.success(resultMap);
        } catch (BusinessException e) {
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.getSession().removeAttribute(Constant.CURRENT_USER_KEY);
            logger.error("检查二维码异常", e);
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("检查二维码异常", e);
            return AjaxResult.error("检查二维码异常");
        }
    }
}
